package com.yinxing.netty.handler;

import com.yinxing.netty.utils.NettyUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.ReadTimeoutException;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class ExceptionHandler extends ChannelInboundHandlerAdapter {

    public static final ExceptionHandler INSTANCE = new ExceptionHandler();

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        final Channel channel = ctx.channel();
        final String remoteHostPort = NettyUtils.getRemoteHostPort(channel);
        if(cause instanceof ReadTimeoutException) {
            log.info("客户端心跳超时.关闭连接 -> {{}}", remoteHostPort);
            return;
        }

        ctx.channel().close();
        log.info(cause.getMessage());
    }
}
